package org.restorator.controller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import org.restorator.entity.AnonymClientOrder;
import org.restorator.entity.Order;
import org.restorator.service.OrderService;
import org.restorator.service.impl.OrderServiceImpl;
import org.restorator.utill.ControllerUtil;
import org.restorator.utill.GeneralUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.List;

import static org.restorator.utill.ControllerUtil.getUrlIdMatch;
import static org.restorator.utill.ControllerUtil.printError;
import static org.restorator.utill.ControllerUtil.printOk;

/**
 * Controller for work with REST style bulk requests on entity {@link Order}.
 *
 * @author Snisar Bogdan.
 */
@WebServlet(name = "orderAll", urlPatterns = "/order")
public class OrderAllController extends HttpServlet {
    private static Logger logger = LoggerFactory.getLogger(GeneralUtil.getClassName());

    private static final String PARAM_SEPARATOR = "=";

    @Override
    public void init() throws ServletException {
        super.init();
        orderService = new OrderServiceImpl();
    }

    private OrderService orderService;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            List<Order> orders = orderService.getAll();
            resp.setContentType("application/json");

            if(orders != null && !orders.isEmpty()) {
                logger.debug("Get request. All ok, find  tables: {}. Dispatch", orders);
                ControllerUtil.printOk(resp.getWriter(), orderService.toDto(orders));
            } else{
                ControllerUtil.printError(resp.getWriter());
            } 
        } catch (Exception e) {
            logger.error("Exception in request processing: {}. \nStack : {}", e.getMessage(), e);
//            if exception - send 404 error
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            logger.debug("Post request");

            BufferedInputStream bf = new BufferedInputStream(req.getInputStream(), 1024*2);
            InputStreamReader reader = new InputStreamReader(bf, "UTF-8");

            StringBuilder builder = new StringBuilder();
            int value;
            while ((value = reader.read()) != -1) {
                builder.append((char) value);
            }
            String bodyRequest = builder.toString();
            logger.debug("POST body request: {}", bodyRequest);

            String tableResult = bodyRequest.substring(bodyRequest.indexOf(PARAM_SEPARATOR)+1, bodyRequest.length());
            Integer tableOrder = new Integer(tableResult);

            Order order = orderService.getOrderByTableId(tableOrder);
            logger.debug("get order by tableId {}, and try find order: {}", tableResult, order);

            printOk(resp, order);
        } catch (Exception ex) {
            printError(resp);
            logger.error("Exception in doPut(): {}", ex);
        }


    }
}
